package com.qilu.pe.ui.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.CustomListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.UriUtils;
import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.qilu.pe.R;
import com.qilu.pe.base.Base2Activity;
import com.qilu.pe.base.BaseResult2;
import com.qilu.pe.base.Config;
import com.qilu.pe.base.Global;
import com.qilu.pe.base.MyApp;
import com.qilu.pe.base.PayResult;
import com.qilu.pe.dao.bean.ExpertUser;
import com.qilu.pe.dao.bean.ImageUrl;
import com.qilu.pe.dao.bean.OrderResult;
import com.qilu.pe.dao.bean.RequestExpertDetails;
import com.qilu.pe.dao.bean.UPayInfo;
import com.qilu.pe.dao.bean.WxPayInfo;
import com.qilu.pe.dao.http.APIRetrofit;
import com.qilu.pe.support.util.ActiviceCollector;
import com.qilu.pe.support.util.AlertUtil;
import com.qilu.pe.support.util.GlobalReqUtil;
import com.qilu.pe.support.util.Logg;
import com.qilu.pe.support.util.PermissionUtil;
import com.qilu.pe.support.util.SelectDialog;
import com.qilu.pe.ui.adapter.ImagePickerAdapter;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.ToastUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

// 申请专家解读
public class ConfirmExpertExplainActivity extends Base2Activity implements ImagePickerAdapter.OnRecyclerViewItemClickListener{
    private AppCompatEditText et_height, et_weight, et_heart, et_temp, et_shrink;
    private AppCompatEditText et_relax, et_family, et_treat, et_pill, et_allergy;
    private AppCompatEditText et_content;// 不适及临床表现
    private TextView tv_name, tv_ok;
//    private ImageView iv_img;

    private String expert, orderId, sid;
    private String expertName,height, weight, heart, temp, shrink, relax, family, treat, pill, allergy;
    private String content;// 不适及临床表现
//    private String[] imgs;

    private ExpertUser currExpert;// 记录当前选择的专家

    IWXAPI msgApi;
    private String order_num;// 创建专家解读的订单号
    private MultipartBody mImageBody;
    private RequestExpertDetails details;

    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;

    private ImagePickerAdapter adapter;
    private ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int maxImgCount = 9;               //允许选择图片最大数
    private boolean isExistImage=false;
    private List<String> uploadImageList=new ArrayList<>();
    @Override
    protected int getLayoutRes() {
        return R.layout.activity_confirm_expert_explain;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActiviceCollector.addActivity(this);
        et_height = findViewById(R.id.et_height);
        et_weight = findViewById(R.id.et_weight);
        et_heart = findViewById(R.id.et_heart);
        et_temp = findViewById(R.id.et_temp);
        et_shrink = findViewById(R.id.et_shrink);
        et_relax = findViewById(R.id.et_relax);
        et_family = findViewById(R.id.et_family);
        et_treat = findViewById(R.id.et_treat);
        et_pill = findViewById(R.id.et_pill);
        et_allergy = findViewById(R.id.et_allergy);
        et_content = findViewById(R.id.et_content);
        tv_name = findViewById(R.id.tv_name);
        tv_ok = findViewById(R.id.tv_ok);
//        iv_img = findViewById(R.id.iv_img);
        initWidget();
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            orderId = bundle.getString("orderId");
            sid = bundle.getString("sid");

            showProgress();
            getRequestDetails();
        }
        setHeadTitle("申请专家解读");

        setListeners();

        alert = new AlertDialog.Builder(this, R.style.Dialog_FS).create();
        alert2 = new AlertDialog.Builder(this, R.style.Dialog_FS).create();
        msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(Config.WX_APP_ID);
        alert.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                // 未支付返回提示信息：您的订单未支付，请尽快完成支付。
                // 继续支付按钮/确认离开按钮，点击确认离开跳转到我的订单列表页
                showDialog2();
            }
        });
    }
    private void initWidget() {
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);

        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);
    }
    private void setListeners() {
        setOnClickListener(tv_name, tv_ok);
    }
    private SelectDialog showDialog3(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }
    ArrayList<String> existImageList = new ArrayList<>();
    public void getRequestDetails() {
        APIRetrofit.getDefault().getRequestExpertDetails(Global.HEADER, orderId)
                .compose(RxUtil.<BaseResult2<List<RequestExpertDetails>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<RequestExpertDetails>>>() {
                    @Override
                    public void accept(BaseResult2<List<RequestExpertDetails>> res) throws Exception {
                        hideProgress();
                        if (res.isSuccess() && res.getData() != null && res.getData().size() > 0) {
                            details = res.getData().get(0);
//                            if(details.getStatus()!=0){
                                if(details.getImage().size()>0){
                                    for(int t=0;t<details.getImage().size();t++){
                                        existImageList.add(Config.URL_IMG +details.getImage().get(t));
                                        uploadImageList.add(details.getImage().get(t));
                                    }
                                    if(existImageList.size()>0){
                                        isExistImage=true;
                                    }else{
                                        isExistImage=false;
                                    }
//                                    adapter.setExistImages(existImageList,isExistImage,details.getStatus());
                                    adapter.setExistImages(existImageList,isExistImage);
//                                    Glide.with(ConfirmExpertExplainActivity.this).load(Config.URL_IMG + details.getImage().get(0)).into(iv_img);

                                }
//                            }
                            //已支付
                            if (2 != details.getStatus()) {
                                tv_ok.setVisibility(View.GONE);
                                et_height.setEnabled(false);
                                et_weight.setEnabled(false);
                                et_heart.setEnabled(false);
                                et_temp.setEnabled(false);
                                et_shrink.setEnabled(false);
                                et_relax.setEnabled(false);
                                et_family.setEnabled(false);
                                et_treat.setEnabled(false);
                                et_pill.setEnabled(false);
                                et_allergy.setEnabled(false);
                                et_content.setEnabled(false);
//                                iv_img.setOnClickListener(null);
                            }
                            expert=String.valueOf(details.getEid());
                            tv_name.setText(details.getEname());
                            et_height.setText(details.getHeight());
                            et_weight.setText(details.getWeight());
                            et_heart.setText(details.getHeart());
                            et_temp.setText(details.getTemperature());
                            String[] bloodArray = new String[2];
                            if (details.getBlood().contains("-")) {
                                bloodArray = details.getBlood().split("-");
                            } else if (details.getBlood().contains(",")) {
                                bloodArray = details.getBlood().split(",");
                            }
                            et_shrink.setText(bloodArray[0]);
                            et_relax.setText(bloodArray[1]);
                            et_family.setText(details.getFamily());
                            et_treat.setText(details.getTreatment());
                            et_pill.setText(details.getDrug());
                            et_allergy.setText(details.getAllergy());
                            et_content.setText(details.getText());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }
    private AlertDialog alert2;// 弹窗
    private View alert_view2;
    public void showDialog2() {// 弹窗
        alert2.show();
        alert_view2 = View.inflate(this, R.layout.layout_alert_com_alert, null);

        TextView tv_1 = alert_view2.findViewById(R.id.tv_1);
        TextView tv_2 = alert_view2.findViewById(R.id.tv_2);
        TextView tv_title = alert_view2.findViewById(R.id.tv_title);
        tv_1.setText("继续支付");
        tv_2.setText("确认离开");
        tv_title.setText("您的订单未支付，请尽快完成支付。");
        tv_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert2.dismiss();
                showDialog();
            }
        });
        tv_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alert2.dismiss();
                finish();
            }
        });

        AlertUtil.setAlertCenterStyle(alert2.getWindow(), alert_view2, this);
    }
    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == tv_name) {// 点击先请求专家列表,再弹出专家选择器
            hideProgress();
            reqExpertList();
            showProgress();
        }
//        if (v == iv_img) {
//            ImagePicker picker = ImagePicker.getInstance();
//            picker.setCrop(false);
//            picker.setSelectLimit(9);
//            Intent intent = new Intent(this, ImageGridActivity.class);
//            startActivityForResult(intent, 1901);
//        }
        if (v == tv_ok) {// 去支付
            height = et_height.getText().toString().trim();
            weight = et_weight.getText().toString().trim();
            heart = et_heart.getText().toString().trim();
            temp = et_temp.getText().toString().trim();
            shrink = et_shrink.getText().toString().trim();
            relax = et_relax.getText().toString().trim();
            family = et_family.getText().toString().trim();
            treat = et_treat.getText().toString().trim();
            pill = et_pill.getText().toString().trim();
            allergy = et_allergy.getText().toString().trim();
            content = et_content.getText().toString().trim();
            expertName=tv_name.getText().toString().trim();
            if (TextUtils.isEmpty(expertName)) {
                ToastUtils.showShort("请选择专家");
                return;
            }
            if (TextUtils.isEmpty(height)) {
                ToastUtils.showShort("请输入您的身高");
                return;
            }
            if (TextUtils.isEmpty(weight)) {
                ToastUtils.showShort("请输入您的体重");
                return;
            }
            if (TextUtils.isEmpty(heart)) {
                ToastUtils.showShort("请输入您的心率");
                return;
            }
            if (TextUtils.isEmpty(temp)) {
                ToastUtils.showShort("请输入您的体温");
                return;
            }
            if (TextUtils.isEmpty(shrink)) {
                ToastUtils.showShort("请输入您的收缩压");
                return;
            }
            if (TextUtils.isEmpty(relax)) {
                ToastUtils.showShort("请输入您的舒张压");
                return;
            }
            if (TextUtils.isEmpty(family)) {
                ToastUtils.showShort("请输入家族史");
                return;
            }
            if (TextUtils.isEmpty(treat)) {
                ToastUtils.showShort("请输入治疗史");
                return;
            }
            if (TextUtils.isEmpty(pill)) {
                ToastUtils.showShort("请输入用药史");
                return;
            }
            if (TextUtils.isEmpty(allergy)) {
                ToastUtils.showShort("请输入过敏史");
                return;
            }
            if (TextUtils.isEmpty(content)) {
                ToastUtils.showShort("请填写不适及临床表现");
                return;
            }


//            if (mImageBody != null) {
//                uploadImage();
//            } else {
                reqCreateExpertOrder();
//            }
        }
    }

//    private void uploadImage() {
////        showProgress();
//        GlobalReqUtil.reqUploadImage(mImageBody, new GlobalReqUtil.OnReqCallBack() {
//            @Override
//            public void onReqResult(BaseResult2<List<ImageUrl>> baseResult2) {
////                hideProgress();
//                if (baseResult2.isSuccess()) {
//                    uploadImageList.add(baseResult2.getData().get(0).getImg());
//                    Logg.e("==图片上传成功=="+baseResult2.getData().get(0).getImg());
////                    reqCreateExpertOrder(baseResult2.getData().get(0).getImg());
//                }
//            }
//
//            @Override
//            public void onReqException(Throwable throwable) {
//                hideProgress();
//                throwable.printStackTrace();
//            }
//        });
//    }

    private void reqCreateExpertOrder() {
        final String blood = shrink + "-" + relax;
//        imgs = new String[]{imgUrl};
        showProgress();
        APIRetrofit.getDefault().reqCreateExpertOrder(Global.HEADER, expert, height, weight
                , heart, temp, blood, family, treat, pill, allergy, content, orderId, sid, uploadImageList)
                .compose(RxUtil.<BaseResult2<List<OrderResult>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<OrderResult>>>() {
                    @Override
                    public void accept(BaseResult2<List<OrderResult>> result2) throws Exception {
                        hideProgress();
                        if (result2.isSuccess()) {
                            if (result2.getData() != null && result2.getData().size() > 0) {
                                OrderResult order = result2.getData().get(0);
                                order_num = order.getOrder_num();
                                showDialog();
                            }
                        } else {
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }


    private Disposable reqExpertList() {
        return APIRetrofit.getLs().reqExpertList(Global.HEADER, 1, 999999)
                .compose(RxUtil.<BaseResult2<List<ExpertUser>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<ExpertUser>>>() {
                    @Override
                    public void accept(BaseResult2<List<ExpertUser>> listBaseResult2) throws Exception {
                        hideProgress();
                        if (listBaseResult2.isSuccess()) {
                            typeList = (ArrayList<ExpertUser>) listBaseResult2.getData();
                            initCustomOptionPicker();
                            pvCustomOptions.show();
                        } else {

                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private ArrayList<ExpertUser> typeList = new ArrayList<>();

    private OptionsPickerView pvCustomOptions;// 条件选择器

    /**
     * @description 注意事项：自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针。
     * 具体可参考demo 里面的两个自定义layout布局。
     */
    private void initCustomOptionPicker() {//条件选择器初始化，自定义布局
        pvCustomOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = typeList.get(options1).getPickerViewText();
                tv_name.setText(tx);
                currExpert = typeList.get(options1);
                expert = currExpert.getId();
            }
        }).setLayoutRes(R.layout.pickerview_custom_options, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = v.findViewById(R.id.tv_finish);
                ImageView ivCancel = v.findViewById(R.id.iv_cancel);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.returnData();
                        pvCustomOptions.dismiss();
                    }
                });

                ivCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.dismiss();
                    }
                });
            }
        })
                .isDialog(true)
                .setOutSideCancelable(false)
                .build();

        pvCustomOptions.setPicker(typeList);//添加数据
    }

    private AlertDialog alert;// 弹窗
    private View alert_view;
    String payType = "2";// 支付方式 1 微信,2 支付宝,3 银联支付,4 余额支付

    public void showDialog() {// 弹窗界面
        alert.show();
        alert_view = View.inflate(this, R.layout.layout_alert_choose_pay_type, null);

        final RadioButton cb_ali = alert_view.findViewById(R.id.cb_ali);
        final RadioButton cb_wx = alert_view.findViewById(R.id.cb_wx);
        final RadioButton cb_union = alert_view.findViewById(R.id.cb_union);
        final RadioButton cb_balance = alert_view.findViewById(R.id.cb_balance);
        final TextView tv_balance0 = alert_view.findViewById(R.id.tv_balance0);// 显示余额数量

        RelativeLayout rl_ali = alert_view.findViewById(R.id.rl_ali);
        RelativeLayout rl_wechat = alert_view.findViewById(R.id.rl_wechat);
        RelativeLayout rl_union_pay = alert_view.findViewById(R.id.rl_union_pay);
        RelativeLayout rl_balance = alert_view.findViewById(R.id.rl_balance);

        tv_balance0.setText("余额支付 (¥" + Global.ORG_BALANCE + ")");

        rl_ali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(true);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        cb_ali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(true);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        rl_wechat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(true);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        cb_wx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(true);
                cb_union.setChecked(false);
                cb_balance.setChecked(false);
            }
        });
        rl_union_pay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(true);
                cb_balance.setChecked(false);
            }
        });
        cb_union.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(true);
                cb_balance.setChecked(false);
            }
        });
        rl_balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(true);
            }
        });
        cb_balance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cb_ali.setChecked(false);
                cb_wx.setChecked(false);
                cb_union.setChecked(false);
                cb_balance.setChecked(true);
            }
        });

        alert_view.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cb_ali.isChecked()) {
                    payType = "2";
                } else if (cb_wx.isChecked()) {
                    payType = "1";
                } else if (cb_union.isChecked()) {
                    payType = "3";
                } else if (cb_balance.isChecked()) {
                    payType = "4";
                }
                if (cb_ali.isChecked()) {// 支付宝
                    hideProgress();
                    reqAliPayInfo();
                    showProgress();
                } else if (cb_wx.isChecked()) {// 微信
                    hideProgress();
                    reqWxPayInfo();
                    showProgress();
                } else if (cb_union.isChecked()) {// 银联
                    hideProgress();
                    reqUPayPayInfo();
                    showProgress();
                } else if (cb_balance.isChecked()) {
                    hideProgress();
                    reqBalancePayInfo();
                    showProgress();
                }
                alert.dismiss();
            }
        });

        AlertUtil.setAlertBottomInStyle(alert.getWindow(), alert_view, this);
    }

    private Disposable reqBalancePayInfo() {
        if (TextUtils.isEmpty(order_num)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqExpertOrderPayBalance(Global.HEADER, order_num, payType)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            startActivity(PaySuccessActivity.class);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_balance = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqUPayPayInfo() {
        if (TextUtils.isEmpty(order_num)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqExpertOrderPayUpay(Global.HEADER, order_num, payType)
                .compose(RxUtil.<BaseResult2<UPayInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<UPayInfo>>() {
                    @Override
                    public void accept(BaseResult2<UPayInfo> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            uPay(baseResult2.getData().getTn());
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_upay = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    private Disposable reqWxPayInfo() {
        if (TextUtils.isEmpty(order_num)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqExpertOrderPayWx(Global.HEADER, order_num, payType)
                .compose(RxUtil.<BaseResult2<WxPayInfo>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<WxPayInfo>>() {
                    @Override
                    public void accept(BaseResult2<WxPayInfo> baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            wxPay(baseResult2);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_wx = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取微信支付信息错误");
                    }
                });
    }

    private Disposable reqAliPayInfo() {
        if (TextUtils.isEmpty(order_num)) {
            ToastUtils.showShort("订单号异常");
            return null;
        }
        return APIRetrofit.getDefault().reqExpertOrderPayAli(Global.HEADER, order_num, payType)
                .compose(RxUtil.<BaseResult2>subIoObMain())
                .subscribe(new Consumer<BaseResult2>() {
                    @Override
                    public void accept(BaseResult2 baseResult2) throws Exception {
                        hideProgress();
                        if (baseResult2.isSuccess()) {
                            String orderInfo = (String) baseResult2.getData();
                            aliPay(orderInfo);
                        } else {
                            ToastUtils.showShort(baseResult2.getMsg());
                        }
                        Logg.i("pay_data_ali = " + baseResult2.getData());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        hideProgress();
                        throwable.printStackTrace();
                    }
                });
    }

    // 调起银联支付
    private void uPay(String tn) {
        UPPayAssistEx.startPay(ConfirmExpertExplainActivity.this, null, null, tn, MyApp.unionPayMode);
    }
    ArrayList<ImageItem> images = null;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
//            if (data != null && requestCode == 1901) {
//                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
//                if (images.size() > 0) {
//                    Logg.i("images.get(0).uri.getPath() = " + images.get(0).uri.getPath());
//                    Glide.with(this).load(images.get(0).uri).into(iv_img);
//                    mImageBody = GlobalReqUtil.generateMultipartBody("id", UriUtils.uri2File(images.get(0).uri));
//                }
//            } else {
//                ToastUtils.showShort("请选择图片");
//            }

            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    for(int m=0;m<images.size();m++){
//                        mImageBody = GlobalReqUtil.generateMultipartBody("picture", UriUtils.uri2File(images.get(m).uri));
//                        File file=UriUtils.uri2File(images.get(m).uri);
//                        uploadImage();
                        File file= new File(images.get(0).uri.getPath());
                        uploadImage1(file);
                    }
                        selImageList.addAll(images);
                        adapter.setImages(selImageList);
                }
            } else {
                ToastUtils.showShort("请选择图片");
            }
        }else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    adapter.setImages(selImageList);
                }
            }
        } else {
            String str = data.getExtras().getString("pay_result");
            if (str.equalsIgnoreCase("success")) {
                //显示支付结果
                ToastUtils.showShort("银联支付成功");
                // 结果为成功时，建议去商户后台查询一下再展示成功
                paySuc();
            } else if (str.equalsIgnoreCase("fail")) {
                ToastUtils.showShort("银联支付失败");
            } else if (str.equalsIgnoreCase("cancel")) {
                ToastUtils.showShort("您取消了银联支付");
            }
        }
    }
    private void uploadImage1(File file) {
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("picture", file.getName(), requestBody);
            GlobalReqUtil.reqUploadImage1(part, new GlobalReqUtil.OnReqCallBack() {
                @Override
                public void onReqResult(BaseResult2<List<ImageUrl>> baseResult2) {
                    if (baseResult2.isSuccess()) {
                        uploadImageList.add(baseResult2.getData().get(0).getImg());
                        Logg.e("==图片上传成功=="+baseResult2.getData().get(0).getImg());
//                    reqCreateExpertOrder(baseResult2.getData().get(0).getImg());
                    }
                }
                @Override
                public void onReqException(Throwable throwable) {
                    hideProgress();
                    throwable.printStackTrace();
                }
            });
    }

    // 调起微信支付
    private void wxPay(BaseResult2<WxPayInfo> baseResult2) {
        WxPayInfo wxPayInfo = baseResult2.getData();
        PayReq request = new PayReq();
        request.appId = wxPayInfo.getAppid();
        request.partnerId = wxPayInfo.getPartnerid();
        request.prepayId = wxPayInfo.getPrepayid();
        request.packageValue = "Sign=WXPay";
        request.nonceStr = wxPayInfo.getNoncestr();
        request.timeStamp = wxPayInfo.getTimestamp();
        request.sign = wxPayInfo.getSign();
        msgApi.sendReq(request);
    }

    // 调起支付宝支付
    private void aliPay(final String orderInfo) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(ConfirmExpertExplainActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = 20100851;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        }).start();
    }

    @SuppressWarnings("all")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            //返回码，标识支付状态，含义如下：9000——订单支付成功 8000——正在处理中 4000——订单支付失败 5000——重复请求 6001——用户中途取消 6002——网络连接出错
            if (msg.what == 20100851) {
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                String payStatus = payResult.getResultStatus();
                if (TextUtils.equals(payStatus, "9000")) {// 判断resultStatus 为9000则代表支付成功
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    ToastUtils.showShort("支付成功");
                    paySuc();

                } else if (TextUtils.equals(payStatus, "6001")) {
                    ToastUtils.showShort("取消支付");
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    ToastUtils.showShort("支付失败");
                }
            }
        }
    };

    private void paySuc() {
        Bundle bundle = new Bundle();
        bundle.putString("from", "expert");// 标识支付来源
        startActivity(PaySuccessActivity.class, bundle);
        finish();
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                final List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                PermissionUtil.handleMultiPermission(this, "读写",
                        new PermissionUtil.PermissionListener() {
                            @Override
                            public void onPermissionOk(boolean isOk) {
                                if (isOk) {
                                    showDialog3(new SelectDialog.SelectDialogListener() {
                                        @Override
                                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                            switch (position) {
                                                case 0: // 直接调起相机
                                                    /**
                                                     * 0.4.7 目前直接调起相机不支持裁剪，如果开启裁剪后不会返回图片，请注意，后续版本会解决
                                                     *
                                                     * 但是当前直接依赖的版本已经解决，考虑到版本改动很少，所以这次没有上传到远程仓库
                                                     *
                                                     * 如果实在有所需要，请直接下载源码引用。
                                                     */
                                                    //打开选择,本次允许选择的数量
//                                                    ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                                                    ImagePicker.getInstance().setSelectLimit(1);
                                                    Intent intent = new Intent(ConfirmExpertExplainActivity.this, ImageGridActivity.class);
                                                    intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                                    startActivityForResult(intent, REQUEST_CODE_SELECT);
                                                    break;
                                                case 1:
                                                    //打开选择,本次允许选择的数量
//                                                    ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                                                    ImagePicker.getInstance().setSelectLimit(1);
                                                    Intent intent1 = new Intent(ConfirmExpertExplainActivity.this, ImageGridActivity.class);
                                                    /* 如果需要进入选择的时候显示已经选中的图片，
                                                     * 详情请查看ImagePickerActivity
                                                     * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                                                    startActivityForResult(intent1, REQUEST_CODE_SELECT);
                                                    break;
                                                default:
                                                    break;
                                            }

                                        }
                                    }, names);
                                } else {
                                    ToastUtils.showShort("权限不足");
                                }
                            }

                            @Override
                            public void onOpenPermissionPage(boolean isOpen) {

                            }
                        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                break;
            default:
                if(isExistImage){
                    Logg.e("===已解读时--图片点击事件==");
                }else{
                    //打开预览
                    Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                    intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                    intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                    intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                    startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                }

                break;
        }
    }
}